package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.*;
import cn.itsource.ymcc.dto.DateAndCode;
import cn.itsource.ymcc.dto.RegisterDTO;
import cn.itsource.ymcc.feign.LoginFeign;
import cn.itsource.ymcc.mapper.UserMapper;
import cn.itsource.ymcc.result.JSONResult;
import cn.itsource.ymcc.service.*;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.BitStatesUtils;
import cn.itsource.ymcc.util.StrUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.invoke.empty.Empty;

import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author Eric Chen
 * @since 2022-07-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private LoginFeign loginFeign;
    @Autowired
    private IUserAccountService iUserAccountService;
    @Autowired
    private IUserBaseInfoService iUserBaseInfoService;
    @Autowired
    private IUserCodeService iUserCodeService;
    @Autowired
    private IUserGrowLogService iUserGrowLogService;
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void register(RegisterDTO dto) {
        DateAndCode o = (DateAndCode)redisTemplate.opsForValue().get(dto.getMobile());
        AssertUtil.isNotNull(o,"验证码过期");
        AssertUtil.isTrue(dto.getSmsCode().equalsIgnoreCase(o.getCode()),"验证码不正确");

        EntityWrapper<User> wrapper = new EntityWrapper<>(); // 根据手机号查询用户
        wrapper.eq("phone", dto.getMobile());
        User user = iUserService.selectOne(wrapper);
        AssertUtil.isNull(user,"手机号已注册");



        Login login = new Login();
        login.setPassword(dto.getPassword());
        login.setType(dto.getRegChannel());
        login.setUsername(dto.getMobile());
        JSONResult save = loginFeign.save(login);
        AssertUtil.isTrue(save.isSuccess(),"注册失败");
        Long loginId = Long.valueOf(save.getData().toString());

        Date date = new Date();
        user = new User();
        user.setPhone(dto.getMobile());
        user.setLoginId(loginId);
        user.setNickName(dto.getMobile());
        user.setSecLevel(0);
        user.setCreateTime(date.getTime());
        Long l = BitStatesUtils.addState(0L, BitStatesUtils.OP_REGISTED);
        l = BitStatesUtils.addState(l, BitStatesUtils.OP_ACTIVED);
        l = BitStatesUtils.addState(l, BitStatesUtils.OP_AUTHED_PHONE);
        user.setBitState(l);
        insert(user);

        UserCode userCode = new UserCode();
        userCode.setUserId(user.getId());
        userCode.setCode(StrUtils.getComplexRandomString(4));
        iUserCodeService.insert(userCode);

        UserAccount account = new UserAccount();
        account.setId(user.getId());
        account.setCreateTime(date.getTime());
        iUserAccountService.insert(account);

        if (StringUtils.isNotEmpty(dto.getCode())) {
            EntityWrapper<UserCode> wrapper1 = new EntityWrapper<>(); // 邀请码检测
            wrapper1.eq("code", dto.getCode());
            UserCode userCode1 = iUserCodeService.selectOne(wrapper1);
            Long userId = userCode1.getUserId();
            EntityWrapper<UserBaseInfo> wrapper2 = new EntityWrapper<>();
            wrapper2.eq("refer_id", userId);
            UserBaseInfo userBaseInfo = iUserBaseInfoService.selectOne(wrapper2);
            AssertUtil.isNull(userBaseInfo, "邀请码已使用");

            UserBaseInfo baseInfo = new UserBaseInfo();
            baseInfo.setId(user.getId());
            baseInfo.setCreateTime(date.getTime());
            baseInfo.setRegChannel(dto.getRegChannel());
            baseInfo.setReferId(userId);
            iUserBaseInfoService.insert(baseInfo);

            UserGrowLog userGrowLog = new UserGrowLog();
            userGrowLog.setCreateTime(date.getTime());
            userGrowLog.setFromReason("推荐码");
            userGrowLog.setUserId(userId);
            userGrowLog.setScore(100);
            iUserGrowLogService.insert(userGrowLog);
        }
        //删除短信验证码
        redisTemplate.delete(dto.getMobile());
    }
}
